<template>
<div class="AAA" style="width: 100%;">
  <div style="height: 100vh;" class="main-search-body" >
      <div class="chat-big-box">
        <div class="chat-left menu-demo">
          <a-menu v-model="activeNames"
                  :style="{ width: '200px', height: '100%' }"
                  :default-open-keys="['0']"
                  :default-selected-keys="['0']"
                  show-collapse-button
                  breakpoint="xl"
                  @collapse="onCollapse">
            <a-sub-menu key="0" >
              <template #icon><icon-apps></icon-apps></template>
              <template #title>
                <div class="online-personnel user-select">
                  <div>沟通过</div>
                  <div class="sum">{{userArr.length>0?userArr.length:0}}人</div>
                </div>
              </template>
              <div class="chat-user-name user-select"
                   v-for="(item,index) in userArr" :key="item.username"
                   v-show="index>=0"
                   @click="checkUser(item)"
                   :class="{'user-name-check':item.status=='在线'}">
<!--                头像-->
                <div>
                  <a-avatar v-if="BASE_URL+item.userImg.length!=null"><img :src="BASE_URL+item.userImg" style="width: 35px; border-radius: 30px; object-fit: cover;margin-left: 5%;" class="scale"></a-avatar>
                  <el-avatar v-else
                             src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                  />
                  </div>
                <div style="margin-left: -3%;font-size: 16px;margin-top: 13px;">{{item.name}}</div>
                <div>{{item.status}}</div>
              </div>
            </a-sub-menu>
          </a-menu>
        </div>
<!--        右边-->
        <div class="chat-right">
          <div class="content" ref="smgContent">
            <div  v-for="item in msgArr" :key="item">{{item}}</div>
          </div>
          <div class="input-box">
            <el-input
                v-model="textarea"
                @keydown.enter="keydown"
                :autosize="{ minRows: 7, maxRows: 7 }"
                type="textarea"/>
            <el-button type="success"  size="large" plain @click="sendBtn" class="input-btn">发送</el-button>
          </div>
        </div>
      </div>
  </div>
</div>
</template>



<script setup>
//Todo
//需要加的数据：招聘名称，薪资，地点，在聊天时显示头像、对话框
import {ref, defineExpose, nextTick, onMounted} from 'vue'
import axios from 'axios'
import qs from "qs";
import {ElMessage} from "element-plus";

const dialogVisible = ref(true)
const smgContent = ref()
const textarea = ref('')
let chatWS = null
const user = ref(getUser());
const username= user.value.username;
console.log(username);
let toUser = {id:null,name:null} // 要发送人的ID
const userArr = ref([]) // 人员数组
const activeNames = ref(['0'])
const msgArr = ref([])
// connectWebSocket()
onMounted(() => {
  connectWebSocket()
  obtainName() // 调取人员接口
})
function connectWebSocket () {
  console.log('connectWebSocket');
  // 判断当前浏览器是否支持WebSocket
  dialogVisible.value = true
  if ('WebSocket' in window) {
    // chatWS = new WebSocket('ws://172.16.26.37:8081/websocket/' + username)0
    console.log(username)
    console.log(username.value)
    // let socketUrl = "ws://localhost:8080/websocket/" + username;
    chatWS = new WebSocket('ws://localhost:8080/websocket/'+username)

  } else {
    alert('当前浏览器不支持Websocket')
  }
  chatWS.onmessage = (evt) => {
    console.log(evt.data,'人员更新');
    if (evt.data==='人员更新') {
      obtainName() // 调取人员接口
    }else{
      console.log("xxxxxxxxxxxxxxxxx")
      console.log(evt.data);
      msgArr.value.push(evt.data)
    }
    // nextTick(()=>{
    //   smgContent.value.scrollTop = smgContent.value.scrollHeight
    // })
  }
}

// 获取聊天人员接口
function obtainName () {
  // axios.get('http://172.16.26.37:8002/java_backend/members').then(res => {
  axios.post('http://localhost:8080/v1/chat/members/'+username).then(res => {
    userArr.value = res.data.data.map(item => {
          item.isCheck = false
          if (toUser.id === item.username) {
            item.isCheck = true
          }
          return item
        },
    console.log(userArr.value)
    )
  })
}

// 选择群聊或者单聊  获取聊天记录
function checkUser (item) {
  console.log("wwwwwwww"+item.username);
  msgArr.value = [] // 清空聊天框内容
  userArr.value.forEach(i => {
    if (i.username !== item.username) {
      i.isCheck = false
    }
  })
  // 保存 选择人员的ID和name 并通过id 来区分是群聊还是单聊
  item.isCheck = !item.isCheck
  toUser.username = item.username
  console.log("66666"+toUser.name)
  if (item.isCheck) {
    toUser.id = item.username
    console.log("1111111"+toUser.id);
    console.log("222222"+item.username)
  } else {
    toUser.id = ''
  }
  let data = qs.stringify({
    type: toUser.id === '' ? 0 : 1,
    toUser:toUser.id,
    fromUser:username
  });
  console.log('获取聊天记录');
  console.log(data);

  // 获取聊天记录
  axios.post('http://localhost:8080/v1/chat/message',data).then(res => {
    let type =toUser.id === '' ? true : false
    if (type) {
      res.data.data.forEach(item=>{
        msgArr.value.push(`${item.fromName}：${item.message}`) // 群聊
      })
    }else{
      if (Array.isArray(res.data.data)) {
        res.data.data.forEach(item => {
          msgArr.value.push(`${item.fromName}->${item.toName}：${item.message}`); // 单聊
        });
      } else {
        console.error('数据不是数组:', res.data.data);
      }
    }
    // nextTick(()=>{
    //   smgContent.value.scrollTop = smgContent.value.scrollHeight
    // })
  })
}
// 发送消息
function keydown(e) {
  if (e.ctrlKey && e.keyCode === 13) {
    // 换行
    textarea.value = textarea.value + '\n'
  }
  if (e.ctrlKey === false && e.keyCode === 13) {
    // 阻止浏览器默认行为  禁止发送时输入框换行
    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
    // 发送
    sendBtn()
  }
}

function sendBtn () {
  if (!toUser.id){
    ElMessage.error("请先选择对象")
    return
  }
  if (textarea.value !== '') {
    const socketMsg = {msg: textarea.value,toUser:toUser.id,type: toUser.id === '' ? 0 : 1}
    chatWS.send(JSON.stringify(socketMsg))
    textarea.value = ''
  }
}
// 关闭连接
function closeWebSocket () {
  chatWS.close()
  userArr.value = []
  textarea.value = ''
  msgArr.value = []
  dialogVisible.value = false
}
// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function () {
  chatWS.close()
}
defineExpose({
  connectWebSocket
})
</script>
<style lang='css' scoped>
.main-search-body {
  width: 80%;
  margin: 0 auto;
}
.menu-demo {
  box-sizing: border-box;
  width: 100%;
  height: 600px;
  padding: 40px;
  background-color: var(--color-neutral-2);
}
</style>
<style lang='less'>

.chat-big-box{
  .user-select{
    user-select:none;
  }
  width: 100%;
  height: 90vh;
  display: flex;
  .chat-left{
    flex: 2;
    padding: 10px;
    border: solid 1px #ccc;
    overflow:auto;
    margin-right: 4px;
    margin-top: 30px;
    background-color: #ffffff;
    border-radius: 15px;
    .user-name-check{
      background: #ffffff !important;
    }
    .chat-user-name{
      display: flex;
      padding: 10px;
      line-height: 14px;
      font-size: 15px;
      div:nth-child(1){
        margin-right: 10px;
      }
      div:nth-child(2){
        width: 150px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        text-align: left;
      }
    }
  }
  .chat-right{
    flex: 4;
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    position: relative;
    background-color: #ffffff;
    border-radius: 15px;
    border: solid 1px #ccc;
    .content{
      width: 100%;
      height: 80%;
      text-align: left;
      overflow: auto;
      margin-bottom: 10px;
      div{
        margin: 100px;
      }
    }
    .input-box{
      width: 100%;
    }
    .input-btn{
      position: absolute;
      right: 10px;
      float: right;
      width: 30px;
      margin-top: -1000px;
      margin-left:80px;
      bottom: 1px;
    }
  }
  ::-webkit-scrollbar {
    width: 4px;
  }
  ::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 8px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #4da1ff;
  }
  ::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 8px;
  }
}
.online-personnel{
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 10px;

  .sum{
    margin-right: 10px;
  }
}
.AAA{
  width: 100%;
  height: 100%;
  min-height: 94vh;
  background-size: 100% 100%;
  background: linear-gradient(-135deg, #4f03ab, #8661f5, #fcfcfc);
  background-size: 200% 200%;
  animation: moveAnimation 4s infinite;
  max-height: 180vh;
}
@keyframes moveAnimation {
  0% {
    background-position: 0% 50%
  }
  50% {
    background-position: 100% 70%
  }
  100% {
    background-position: 0% 50%
  }
}
</style>